﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using WSS.BLL.Account;
using WSS.Models.User;
using WSS.Pub;

namespace WSS.Web.Controllers
{
    public class MyAuthorize : AuthorizeAttribute
    {
        /// <summary>
        /// 是否通过授权检查
        /// </summary>
        private bool IS_AUTHORIZE_SUCCESS = true;

        /// <summary>
        /// 自定义授权检查
        /// </summary>
        /// <param name="httpContext"></param>
        /// <returns></returns>
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {

            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }

            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }

            string userdata = ((System.Web.Security.FormsIdentity)(httpContext.User.Identity)).Ticket.UserData;

            if (string.IsNullOrEmpty(userdata))
            {
                return false;
            }

            string[] arr_userdata = userdata.Split(',');

            if (arr_userdata.Length != 4)
            {
                return false;
            }

            string guid = arr_userdata[0];
            string userid = arr_userdata[1];
            string userno = arr_userdata[2];
            string hospitalid = arr_userdata[3];

            //登录数据丢失
            if (UserOnline.GetOnlineUserByUserId(userid) == null)
            {
                return false;
            }

            return base.AuthorizeCore(httpContext);
        }

        /// <summary>
        /// 授权检查结束后，执行本方法
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            base.HandleUnauthorizedRequest(filterContext);

            if (filterContext.HttpContext.Response.StatusCode == 401)
            {
                filterContext.Result = new RedirectResult("/Login/Login");
            }

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new JsonResult
                    {
                        Data = new { flag = false, msg = "登录超时，请重新登录再操作！" },
                        JsonRequestBehavior = JsonRequestBehavior.AllowGet
                    };
            }

            if (!IS_AUTHORIZE_SUCCESS)
            {

            }

            //最后
            //<authentication mode="Forms">
            //  <forms loginUrl="~/Account/LogOn" timeout="2880" />
            //</authentication>
        }
    }
}